/*
 * Created by Julia on 2016/5/06.
 */

define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'appMessageBox'], function ($, domReady, appLocalStorage, appConst, global, msgBox) {
    var that;
    var isFirst = true;
    return {
        init: function () {
            that = this;
        },
        canAddRoles: function ($this, d) {
            var $this = $this;
            $this.each(function (i, e) {
                var resourceId = $(this).attr('permissionId');
                var resourceCode = $(this).attr('permissionCode');
                var $that = $(this);
                that.showCanAddRole(resourceId, resourceCode, function (d) {
                    var td = that.format(d, resourceId, resourceCode);
                    //$that.closest('tr').next('tr.edit').html(td);
                    that.setHtml($that.closest('tr').next('tr.edit'), td, function () {
                        that.initPermissionEvent();
                    });

                });
            });
        },
        canAddRolesInFirstMenu: function (elementObject, roleId, d) {
            elementObject.each(function (i, e) {
                var resourceId = $(this).attr('permissionId');
                var resourceCode = $(this).attr('permissionCode');
                var ressourceCodes = resourceCode.split(":");
                if (ressourceCodes.length == 2 && resourceCode.indexOf("*") != -1) {
                    $(this).find('a[roleId=' + roleId + ']').parent().remove();
                    var $this = $(this);
                    that.showCanAddRole(resourceId, resourceCode, function (d) {
                        var td = that.format(d, resourceId, resourceCode);
                        //$this.closest('tr').next('tr.edit').html(td);
                        that.setHtml($this.closest('tr').next('tr.edit'), td, function () {
                            that.initPermissionEvent();
                        });

                    });
                    return false;
                }
            });
        },
        deleteRoleConfirm: function (permissionId, roleId, permissionCode) {
            var ressourceCodes = permissionCode.split(":");
            var isHasParent = 0;
            if (ressourceCodes.length == 2) {
                isHasParent = $("table." + ressourceCodes[0]).find('ul[permissionCode$="*"]').find('a[roleId=' + roleId + ']').length;
            }
            else if (ressourceCodes.length == 3) {
                isHasParent = $("table." + ressourceCodes[0]).find('ul[permissionCode*=' + ressourceCodes[1] + '][permissionCode$="*"]').find('a[roleId=' + roleId + ']').length;
            }

            if (isHasParent != 0) {
                msgBox.show({
                    title: $.i18n.prop('MESSAGEBOX_CONFIRM_TITLE'),
                    content: $.i18n.prop('MESSAGEBOX_CONFIRM_DELETE_ROLES_OF_PERMISSION_CONTENT') + " <p class='text-align-right'>" +
                    "<button type='submit' roleId='" + roleId + "' permissionId='" + permissionId + "' permissionCode='" + permissionCode + "' class='btn btn-primary btn-sm clearRole_Re"+roleId+"'>" + $.i18n.prop('GLOBAL_BUTTON_YES') + "</button> " +
                    "<a href='javascript:void(0);' class='btn btn-danger btn-sm'>" + $.i18n.prop('GLOBAL_BUTTON_NO') + "</a></p>",
                    type: 'normal',
                    timeout: false,
                    clean: true
                });
                $('#divSmallBoxes').find(".clearRole_Re" + roleId).unbind('click').on('click', function (e) {
                    e.preventDefault();
                    that.clearRole($(this).attr("permissionId"), $(this).attr("roleId"), $(this).attr("permissionCode"));
                });
            } else {
                that.clearRole(permissionId, roleId, permissionCode);
            }

        },
        clearRole: function (permissionId, roleId, permissionCode) {
            $.ajax({
                "url": "permission/clearRole",
                "type": "post",
                "dataType": "json",
                "data": {'permissionId': permissionId, 'roleId': roleId},
                "success": function (d) {
                    if (d.code == 0) {
                        msgBox.errorBox(d.message, d.message != null ? 'MENU_SYSTEM_PERMISSION' : 'EXCEPTION_PERMISSION_ASSIGNED_FAIL');
                        return false;
                    }
                    that.showCanAddRole(permissionId, permissionCode, function (d) {
                        var td = that.format(d, permissionId, permissionCode);
                        var resourceId = permissionId;
                        var resourceCode = permissionCode;
                        var ressourceCodes = resourceCode.split(":");
                        //$("table." + ressourceCodes[0]).find('ul[permissionId=' + permissionId + ']').closest('tr').next('tr.edit').html(td);
                        that.setHtml($("table." + ressourceCodes[0]).find('ul[permissionId=' + permissionId + ']').closest('tr').next('tr.edit'), td, function () {
                            that.initPermissionEvent();
                        });

                        $("table." + ressourceCodes[0]).find('ul[permissionId=' + permissionId + ']').find('a[roleId=' + roleId + ']').parent().remove();

                        //click firstMenu, such as (system:*)
                        if (ressourceCodes.length == 2 && resourceCode.indexOf("*") != -1) {
                            //delete has role
                            $("table." + ressourceCodes[0]).find('a[roleId=' + roleId + ']').parent().remove();
                            //add has role in Can add role
                            //permissions.canAddRoles($("table." +ressourceCodes[0]).find('ul'), d);
                            $("table." + ressourceCodes[0]).find('ul').each(function (i, e) {
                                var resourceId = $(this).attr('permissionId');
                                var resourceCode = $(this).attr('permissionCode');
                                var td = that.format(d, resourceId, resourceCode);
                                //$(this).closest('tr').next('tr.edit').html(td);
                                that.setHtml($(this).closest('tr').next('tr.edit'), td, function () {
                                    that.initPermissionEvent();
                                });
                            });
                        }
                        //click secondMenu(only include one :), such as (project:view)
                        else if (ressourceCodes.length == 2 && resourceCode.indexOf("*") == -1) {
                            $("table." + ressourceCodes[0]).find('ul[permissionCode$="*"]').find('a[roleId=' + roleId + ']').parent().remove();
                            that.canAddRoles($("table." + ressourceCodes[0]).find('ul[permissionCode$="*"]'), d);
                        }
                        //click secondMenu(include two :), such as (system:user:*)
                        else if (ressourceCodes.length == 3 && resourceCode.indexOf("*") != -1) {
                            var elementObject = $("table." + ressourceCodes[0]).find('ul[permissionCode*=' + ressourceCodes[1] + ']');
                            elementObject.find('a[roleId=' + roleId + ']').parent().remove();
                            that.canAddRolesInFirstMenu($("table." + ressourceCodes[0]).find('ul[permissionCode$="*"]'), roleId, d);
                            elementObject.each(function (i, e) {
                                var resourceId = $(this).attr('permissionId');
                                var resourceCode = $(this).attr('permissionCode');
                                var td = that.format(d, resourceId, resourceCode);
                                //$(this).closest('tr').next('tr.edit').html(td);
                                that.setHtml($(this).closest('tr').next('tr.edit'), td, function () {
                                    that.initPermissionEvent();
                                });

                            });
                        }
                        //click thirdMenu(include two :), such as (system:user:view)
                        else if (ressourceCodes.length == 3 && resourceCode.indexOf("*") == -1) {
                            var elementObject = $("table." + ressourceCodes[0]).find('ul[permissionCode*=' + ressourceCodes[1] + '][permissionCode$="*"]');
                            elementObject.find('a[roleId=' + roleId + ']').parent().remove();
                            that.canAddRolesInFirstMenu($("table." + ressourceCodes[0]).find('ul[permissionCode$="*"]'), roleId, d);
                            that.canAddRoles(elementObject, d);
                        }

                    });
                },
                "error": function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        assignRole: function (resourceId, roleId, permissionCode, callback) {
            $.ajax({
                "type": "post",
                "url": 'permission/assignRole',
                "dataType": "json",
                "data": {'resourceId': resourceId, 'roleId': roleId.toString()},
                "success": function (d) {
                    if (d.code == 0) {
                        msgBox.errorBox(d.message, d.message != null ? 'MENU_SYSTEM_PERMISSION' : 'EXCEPTION_PERMISSION_ASSIGNED_FAIL');
                        return false;
                    }
                    callback(resourceId, permissionCode);
                },
                "error": function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        closeRow: function (obj) {
            $(obj).closest('tr').remove();
        },
        showCanAddRole: function (id, permissionCode, callback) {
            $.ajax({
                "url": "permission/ResourceCanAddRole/" + id,
                "type": "POST",
                "success": function (d) {
                    callback(d.body);
                },
                "error": function (e) {
                    if (e.status == 401) {
                        sessionFailureBox();
                    }
                    if (e.status == 500) {
                        serverFailureBox();
                    }
                    if (e.status == 404) {
                        pathFailureBox();
                    }
                }
            });
        },
        btnStyleEvent: function ($this) {
            var $this = $this;
            if ($this.hasClass("btn-warning")) {
                $this.removeClass("btn-warning");
                $this.addClass("btn-danger");
            } else if ($this.hasClass("btn-danger")) {
                $this.removeClass("btn-danger");
                $this.addClass("btn-warning");
            }
        },
        btnPlusEvents: function ($this) {
            var $this = $this;
            if ($this.closest('tr').find('.addRole_Re').hasClass("btn-danger")) {
                var roleIds = new Array();
                var resourceId = $this.attr('permissionId');
                var resourceCode = $this.attr('permissionCode');
                var ressourceCodes = resourceCode.split(":");
                $this.closest('tr').find('.btn-danger').each(function (i, e) {
                    var roleId = $(this).val();
                    var roleName = $(this).text();
                    roleIds.push(roleId);
                });
                that.assignRole(resourceId, roleIds, resourceCode, function (resourceId, resourceCode) {
                    var ressourceCodes = resourceCode.split(":");
                    var $this = $("table." + ressourceCodes[0]).find('ul[permissionId=' + resourceId + ']').closest('tr');
                    if ($this.next('tr.edit').find('.addRole_Re').hasClass("btn-danger")) {
                        var ressourceCodes = resourceCode.split(":");
                        $this.next('tr.edit').find('.btn-danger').each(function (i, e) {
                            var roleId = $(this).val();
                            var roleName = $(this).text();
                            //click firstMenu(only include one :), such as (system:*)
                            if (ressourceCodes.length == 2 && resourceCode.indexOf("*") != -1) {
                                var elementFirstAllObject = $("table." + ressourceCodes[0]);
                                //delete has role
                                elementFirstAllObject.find('a[roleId=' + roleId + ']').parent().remove();
                                //add role for resouce
                                elementFirstAllObject.find('ul').each(function (i, e) {
                                    var resourceId = $(this).attr('permissionId');
                                    var resourceCode = $(this).attr('permissionCode');
                                    that.addNotHaveRoles($(this), roleName, roleId, resourceCode, resourceId, function() {
                                        that.deleteRoleConfirmEvent();
                                    });
                                });
                                //delete role for (Can add role)
                                elementFirstAllObject.find('button[value=' + roleId + ']').remove();
                            }
                            //click secondMenu(only include one :), such as (project:view)
                            else if (ressourceCodes.length == 2 && resourceCode.indexOf("*") == -1) {

                                that.addNotHaveRoles($("table." + ressourceCodes[0]).find('ul[permissionId=' + resourceId + ']'), roleName, roleId, resourceCode, resourceId, function() {
                                    that.deleteRoleConfirmEvent();
                                });

                                //delete role for (Can add role)
                                $this.next('tr.edit').find('button[value=' + roleId + ']').remove();

                                var elementFirstMenu = $("table." + ressourceCodes[0]).find('ul[permissionCode$="*"]');
                                var elementFirstAllObject = $("table." + ressourceCodes[0]).find('ul');

                                var firstNav = elementFirstMenu.find('a[roleId=' + roleId + ']').length;
                                var firstAllSize = elementFirstAllObject.length;
                                var firstHasSize = elementFirstAllObject.find('a[roleId=' + roleId + ']').length;

                                //add role for firstMenu
                                if (firstNav == 0 && firstAllSize == firstHasSize + 1) {
                                    elementFirstMenu.each(function (i, e) {
                                        var resourceId = $(this).attr('permissionId');
                                        var resourceCode = $(this).attr('permissionCode');
                                        var ressourceCodes = resourceCode.split(":");
                                        if (ressourceCodes.length == 2 && resourceCode.indexOf("*") != -1) {
                                            that.addNotHaveRoles($(this), roleName, roleId, resourceCode, resourceId, function() {
                                                that.deleteRoleConfirmEvent();
                                            });
                                            //delete role for (Can add role)
                                            $("table." + ressourceCodes[0]).find('button[value=' + roleId + ']').remove();
                                            return false;
                                        }
                                    });
                                }
                            }
                            //click secondMenu(include two :), such as (system:user:*)
                            else if (ressourceCodes.length == 3 && resourceCode.indexOf("*") != -1) {
                                var elementObject = $("table." + ressourceCodes[0]).find('ul[permissionCode*=' + ressourceCodes[1] + ']');
                                elementObject.find('a[roleId=' + roleId + ']').parent().remove();

                                //add role for subMenu  of secondMenu
                                elementObject.each(function (i, e) {
                                    var resourceId = $(this).attr('permissionId');
                                    var resourceCode = $(this).attr('permissionCode');
                                    that.addNotHaveRoles($(this), roleName, roleId, resourceCode, resourceId, function() {
                                        that.deleteRoleConfirmEvent();
                                    });
                                    $("table." + ressourceCodes[0]).find('button[permissionCode*=' + ressourceCodes[1] + '][value=' + roleId + ']').remove();
                                });
                                that.addNotHaveRolesInFirstMenu(roleName, roleId, resourceCode, resourceId);
                            }
                            //click thirdMenu(include two :), such as (system:user:view)
                            else if (ressourceCodes.length == 3 && resourceCode.indexOf("*") == -1) {
                                that.addNotHaveRoles($("table." + ressourceCodes[0]).find('ul[permissionId=' + resourceId + ']'), roleName, roleId, resourceCode, resourceId, function() {
                                    that.deleteRoleConfirmEvent();
                                });
                                $this.next('tr.edit').find('button[value=' + roleId + ']').remove();

                                var elementSecondObject = $("table." + ressourceCodes[0]).find('ul[permissionCode*=' + ressourceCodes[1] + '][permissionCode$="*"]');
                                var elementSecondAllObject = $("table." + ressourceCodes[0]).find('ul[permissionCode*=' + ressourceCodes[1] + ']');

                                var secondNav = elementSecondObject.find('a[roleId=' + roleId + ']').length;
                                var secondAllSize = elementSecondAllObject.length;
                                var secondHasSize = elementSecondAllObject.find('a[roleId=' + roleId + ']').length;
                                if (secondNav == 0 && secondAllSize == secondHasSize + 1) {
                                    elementSecondObject.each(function (i, e) {
                                        var resourceId = $(this).attr('permissionId');
                                        var resourceCode = $(this).attr('permissionCode');
                                        that.addNotHaveRoles($(this), roleName, roleId, resourceCode, resourceId, function() {
                                            that.deleteRoleConfirmEvent();
                                        });
                                        $("table." + ressourceCodes[0]).find('button[permissionCode*=' + ressourceCodes[1] + '][value=' + roleId + ']').remove();
                                    });
                                }
                                that.addNotHaveRolesInFirstMenu(roleName, roleId, resourceCode, resourceId);
                            }
                        });
                    } else {
                        return false;
                    }
                });
            } else {
                return false;
            }
        },
        addNotHaveRolesInFirstMenu: function (roleName, roleId, resourceCode, resourceId) {
            var ressourceCodes = resourceCode.split(":");
            var firstNav = 0;
            var elementObject = $("table." + ressourceCodes[0]).find('ul[permissionCode$="*"]');
            var firstAllSize = elementObject.length;
            var firstHasSize = elementObject.find('a[roleId=' + roleId + ']').length;
            $("table." + ressourceCodes[0]).find('ul').each(function (i, e) {
                var resourceCode = $(this).attr('permissionCode');
                var ressourceCodes = resourceCode.split(":");
                if (ressourceCodes.length == 2 && resourceCode.indexOf("*") != -1 && $(this).find('a[roleId=' + roleId + ']').length == 1) {
                    firstNav = 1;
                    return false;
                }
            });

            if (firstNav == 0 && firstAllSize == firstHasSize + 1) {
                $("table." + ressourceCodes[0]).find('ul').each(function (i, e) {
                    var resourceId = $(this).attr('permissionId');
                    var resourceCode = $(this).attr('permissionCode');
                    var ressourceCodes = resourceCode.split(":");
                    if (ressourceCodes.length == 2 && resourceCode.indexOf("*") != -1) {
                        that.addNotHaveRoles($(this), roleName, roleId, resourceCode, resourceId, function() {
                            that.deleteRoleConfirmEvent();
                        });
                        $("table." + ressourceCodes[0]).find('button[value=' + roleId + ']').remove();
                        return false;
                    }
                });
            }
        },
        addNotHaveRoles: function ($this, roleName, roleId, resourceCode, resourceId, callback) {
            $this.append('<li class="haveRole">' + roleName + '(<a href="javascript:void(0);" class="deleteRoleConfirm_Re" roleId=\'' + roleId + '\' permissionId="' + resourceId + '" permissionCode=\"' + resourceCode + '\">' + $.i18n.prop("PERMISSION_DELETE") + '' +
                '</a>)</li>');
            if (typeof callback == 'function') {
                callback();
            }
        },
        format: function (canAdd, resourceId, resourceCode) {
            var canAddrole = "";
            $(canAdd).each(function (i, e) {
                canAddrole += '<button class="btn btn-xs btn-warning pull-left addRole_Re"  value="' + e.id + '" permissionId="' + resourceId + '" permissionCode="' + resourceCode + '">' + e.name + '</button> &nbsp;';
            });
            return '<td><span style="float:left;">' + $.i18n.prop('USER_CAN_ADD_ROLE') + '&nbsp;&nbsp;</span>' +
                '<div class="edit_div"> ' +
                '<a href="javascript:void(0);" class="btn btn-success btn-xs plus_Re" permissionId="' + resourceId + '" permissionCode="' + resourceCode + '"><i class="fa fa-plus"></i>&nbsp;</a>'
                + canAddrole +
                '</div>' +
                '</td>' +
                '<td>' +
                '</td>' +
                '<td>' +
                '<a href="javascript:void(0);" class="btnClose_Re">' + $.i18n.prop('GLOBAL_CLOSE') + '</a>' +
                '</td>';
        },
        initPermissionEvent: function () {
            $('table button.addRole_Re').unbind('click').on('click', function (e) {
                e.preventDefault();
                that.btnStyleEvent($(this));
            });

            $('table a.plus_Re').unbind('click').on('click', function (e) {
                e.preventDefault();
                that.btnPlusEvents($(this));
            });

            $('table a.btnClose_Re').unbind('click').on('click', function (e) {
                e.preventDefault();
                that.closeRow($(this));
            });
        },
        setHtml: function (obj, td, callback) {
            obj.html(td);
            if (typeof callback == 'function') {
                callback();
            }
        },
        deleteRoleConfirmEvent: function () {
            $('table a.deleteRoleConfirm_Re').unbind('click').on('click', function (e) {
                e.preventDefault();
                that.deleteRoleConfirm($(this).attr("permissionId"), $(this).attr("roleId"), $(this).attr("permissionCode"), $(this));
            });
        }
    };
});
